import { defineEventHandler } from 'h3'
import { readFile, stat } from 'fs/promises'
// 原代码中尝试从 '@sidebase/nuxt-prisma' 导入名为 'prisma' 的具名导出，但该模块没有这样的具名导出，根据提示修改为默认导入
import {prisma} from '../utils/prisma'


export default defineEventHandler(async (event) => {
  const { code } = await readBody(event)
  
  const validateOnly = event.node.req.url?.includes('validate=true')
  
  const fileRecord = await prisma.file.findUnique({
    where: { code },
    select: {
      fileName: true,
      filePath: true,
      expiresAt: true
    }
  })

  if (!fileRecord || new Date() > fileRecord.expiresAt) {
    throw createError({ 
      statusCode: 404, 
      message: '取件码无效或已过期' 
    })
  }

  if (validateOnly) {
    return {
      fileName: fileRecord.fileName,
      fileSize: (await stat(fileRecord.filePath)).size,
      expiresAt: fileRecord.expiresAt
    }
  }
  
  const fileData = await readFile(fileRecord.filePath)
  
  setResponseHeaders(event, {
    'Content-Length': (await stat(fileRecord.filePath)).size,
    'Content-Type': 'application/octet-stream',
    'Content-Disposition': `attachment; filename="${encodeURIComponent(fileRecord.fileName)}"`
  })

  return fileData
})